import React, { useState } from 'react'
import { Form, Button, Input, Notify } from 'react-vant'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { useAppDispatch } from '../../app/hooks'
import { loginSuccess } from '../../app/user/userSlice'
const Index = () => {
	const navigate = useNavigate()
	const [form] = Form.useForm()
	const [count, setCount] = useState(5);
	const dispatch = useAppDispatch()
	// 获取手机号
	const tel = Form.useWatch('tel', form)

	const getCode = async () => {

		// 发送请求
		const resp = await axios.get('/api/code', { params: { tel } })
		const { code, data, message } = resp.data;

		if (code === 200) {
			// 倒计时
			const timer = setInterval(() => {
				setCount(state => {
					if (state <= 1) {
						clearInterval(timer)
						return 5;
					}
					return state - 1
				})
			}, 1000)
			// 获取验证码
			const { systemCode } = data;
			Notify.show({ type: 'success', message: '您的验证码:' + systemCode })
		} else {
			Notify.show({ type: 'danger', message })
		}
	}

	const onFinish = async (values: any) => {
		const resp = await axios.post('/api/tel/signin', values)
		const { code, data, message } = resp.data;
		if (code === 200) {
			dispatch(loginSuccess({ ...data, isLogin: true }))
			Notify.show({
				type: 'success', message, onClose() {
					navigate(-1)
				}
			});
		} else {
			Notify.show({ type: 'danger', message })
		}

	}

	return (
		<div>
			<Form
				form={form}
				onFinish={onFinish}
				footer={
					<div style={{ margin: '16px 16px 0' }}>
						<Button round nativeType='submit' type='primary' block>
							提交
						</Button>
					</div>
				}
			>
				<Form.Item
					rules={[{ required: true, message: '请填写手机号' }]}
					name='tel'
					label='手机号'
				>
					<Input placeholder='请输入手机号' />
				</Form.Item>
				<Form.Item
					rules={[{ required: true, message: '请填写验证码' }]}
					name='code'
					label='验证码'
				>
					<Input
						suffix={
							<Button disabled={count !== 5} size="small" type="primary" onClick={() => getCode()}>
								{count === 5 ? '发送' : count + 's'}
							</Button>}
						placeholder="请输入短信验证码"
					/>
				</Form.Item>
			</Form>
		</div>
	)
}

export default Index